package com.fingard.dsp.bank.directbank.icbc02;

import java.util.Date;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.ICancelAuthorizeForRec;
import com.fingard.dsp.bank.directbank.icbc41.ICBC41Header;
import com.fingard.dsp.bank.reqrespobj.authcancelforrec.*;
import com.fingard.dsp.bank.reqrespobj.authforrec.detail.RetAtsQryAuthForRecDetail;
import com.fingard.net.ConnState;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

/**
 * Created by F on 2019/3/29.
 */
public class ICBC02AuthorizeCancelForRec extends ICBC02Base implements ICancelAuthorizeForRec {
    @Override
    public RetAtsAuthCancelForRec d_AuthCancel(ReqAuthCancelForRec p_req) throws Exception {
        RetAtsAuthCancelForRec retAts = new RetAtsAuthCancelForRec(p_req.reqHeader);
        try {
            XmlTextWriter xmlWriter = new XmlTextWriter();
            bnkPackageID =p_req.reqSeqID;
            bnkTransCode="ENDIDEL";
            bnkfSeqno =p_req.reqSeqID;
            writeCommonHeader(xmlWriter);
//            /CMS/eb/in/TotalNum	总笔数	必输项	数字	6	指令包内的指令笔数
            xmlWriter.writeElementString("TotalNum",p_req.totalNum);
//                    /CMS/eb/in/ContractNo	协议编号	必输项	字符	15	－
            xmlWriter.writeElementString("ContractNo",getBankConfig().getValueAsString("contractNo"));
//            /CMS/eb/in/AcctNo	企业账号	必输项	字符	19	－
            xmlWriter.writeElementString("AcctNo",p_req.ownAct);
//            /CMS/eb/in/SignTime	签名时间	必输项	数字	17	格式：yyyyMMddHHmmssSSS
            xmlWriter.writeElementString("SignTime", Format.DateTime17Format.format(new Date()));
            int seqNum = 0;
            while (p_req.readRecord()) {
                seqNum++;
                xmlWriter.writeStartElement("rd");
//            /CMS/eb/in/rd/iSeqno	指令顺序号	必输项	字符	35	每笔指令顺序号，本包内不重复（工行只检查包内不重复，不同的包，工行不做指令顺序号重复性的检查）
                xmlWriter.writeElementString("iSeqno",seqNum+"");
//            /CMS/eb/in/rd/PayNo	缴费编号	必输项	字符	30	－
                xmlWriter.writeElementString("PayNo",p_req.readedDetail.authCode);
//            /CMS/eb/in/rd/PayAcctName	缴费客户姓名	选输项	字符	60	快捷支付协议可送空
                xmlWriter.writeElementString("PayAcctName",p_req.readedDetail.oppActName);
//            /CMS/eb/in/rd/PayAccNo	缴费客户账号	选输项	字符	34	快捷支付协议可送空
                xmlWriter.writeElementString("PayAccNo",p_req.readedDetail.oppAct);
                xmlWriter.writeEndElement();
            }
            xmlWriter.writeEndDocument();
            String[] bankResult = sendToBank(xmlWriter.toXmlString(),true);
            if (bankResult[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                //解析银行返回
                XmlTextReader tmpBkReader = loadBankRespXmlReader(bankResult[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/CMS/eb/pub/RetCode");
                    String tmpRetMsg = tmpBkReader.getFirstText("/CMS/eb/pub/RetMsg");
                    if(isActiveRetCode(tmpRetCode)) {
                        retAts.respCode = "0";
                        retAts.respInfo = tmpRetMsg;
                        retAts.reqSeqID = tmpBkReader.getFirstText("/CMS/eb/pub/fSeqno");
                        retAts.serialNo = tmpBkReader.getFirstText("/CMS/eb/pub/SerialNo");
                        String result =tmpBkReader.getFirstText("/CMS/eb/out/rd/Result");
                         if("6".equals(result)||"0".equals(result)){
                             retAts.retCode = "0";
                        } else if("7".equals(result)){
                             retAts.retCode = "1";
                        } else{
                            retAts.respCode = "2";
                            retAts.respInfo = "返回未知的指令码："+result;
                        }
                        retAts.retCode = tmpRetCode;
                        retAts.retMsg = tmpRetMsg;
                    }else{
                        retAts.respCode = "-1";
                        retAts.respInfo = tmpRetMsg;
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = tmpSbMsg.toString();
                }
            } else if (ConnState.FAIL.equals(bankResult[0])) {
                retAts.respCode = "0";
                retAts.respInfo = bankResult[1];
                retAts.reqSeqID = p_req.reqSeqID;
                retAts.retCode = "1";
            } else {
                retAts.respCode = "-1";
                retAts.respInfo =bankResult[1] ;
            }
        }catch (Exception ex){
            ex.printStackTrace();
            retAts.respCode ="-1";
            retAts.respInfo = ex.getMessage();
        }
        retAts.writeRetToATS();
        return retAts;
    }

    @Override
    public RetAtsQryAuthCancelForRec d_qry_AuthCancel(ReqQryAuthCancelForRec p_req) throws Exception {
        RetAtsQryAuthCancelForRec retAts = new RetAtsQryAuthCancelForRec(p_req.reqHeader);
        retAts.writeStart();
        try {
            XmlTextWriter xmlWriter = new XmlTextWriter();
            bnkTransCode = "QENDIDEL";
            bnkPackageID = p_req.reqHeader.transSeqID;
            bnkfSeqno = p_req.reqHeader.transSeqID;
            writeCommonHeader(xmlWriter);
            xmlWriter.writeElementString("QryfSeqno",p_req.reqSeqID);
            xmlWriter.writeElementString("QrySerialNo","");
            xmlWriter.writeEndDocument();
            String[] bankResult = sendToBank(xmlWriter.toXmlString());
            if (bankResult[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                //解析银行返回
                XmlTextReader tmpBkReader = loadBankRespXmlReader(bankResult[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/CMS/eb/pub/RetCode");
                    String tmpRetMsg = tmpBkReader.getFirstText("/CMS/eb/pub/RetMsg");
                    if(isActiveRetCode(tmpRetCode)){
                        retAts.respCode = "0";
                        retAts.respInfo = tmpRetMsg;
                        retAts.reqSeqID = p_req.reqSeqID;
                        retAts.transState = "3";
                        while (tmpBkReader.read("/CMS/eb/out/rd")){
                            RetAtsQryAuthForRecDetail detail =new RetAtsQryAuthForRecDetail();
//                            D8	/CMS/eb/out/rd/iSeqno	所查指令包顺序号	否	字符	35	－
                            detail.iSeqno = tmpBkReader.readedXElement.getSingleText("iSeqno");
//                            D10	/CMS/eb/out/rd/Result	指令状态	否	字符	2	数据字典：0-提交成功，等待银行处理；6-被银行拒绝；7-处理成功；
                            String result=tmpBkReader.readedXElement.getSingleText("Result");
                            if("0".equals(result)){
                                detail.transState ="4";
                            }else if("6".equals(result)){
                                detail.transState ="2";
                            }else if("7".equals(result)){
                                detail.transState ="3";
                            }else{
                                throw new Exception("银行返回的指令状态异常："+result);
                            }
//                            D13	/CMS/eb/out/rd/iRetMsg	明细交易返回描述	否	字符	200	－
                            detail.payInfo = tmpBkReader.readedXElement.getSingleText("iRetMsg");
//                            D14	/CMS/eb/out/rd/PayNo	缴费编号	否	字符	30	－
                            detail.authCode = tmpBkReader.readedXElement.getSingleText("PayNo");
//                            D15	/CMS/eb/out/rd/PayAcctName	缴费客户姓名	否	字符	60	－
                            detail.oppActName =tmpBkReader.readedXElement.getSingleText("PayAcctName");
//                            D16	/CMS/eb/out/rd/PayAccNo	缴费客户账号	否	字符	34	－
                            detail.oppAct =tmpBkReader.readedXElement.getSingleText("PayAccNo");
//                            D17	/CMS/eb/out/rd/ExpireDate	到期日	否	数字	8	格式yyyyMMdd
                            detail.deadLine = DateHelper.convertD8toD10(tmpBkReader.readedXElement.getSingleText("ExpireDate"));
                            retAts.writeRetDetail(detail);
                        }
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = tmpSbMsg.toString();
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo =bankResult[1] ;
            }
        }catch (Exception ex){
            ex.printStackTrace();
            retAts = new RetAtsQryAuthCancelForRec(p_req.reqHeader);
            retAts.respCode ="-1";
            retAts.respInfo = ex.getMessage();
            retAts.writeStart();
            retAts.writeRetHead();
        }
        retAts.writeEnd();
        return retAts;
    }

    @Override
    public RetAtsQryRecAuthCancelInfo d_qry_AuthCancelInfo(ReqQryRecAuthCancelInfo p_req) throws Exception {
        return null;
    }
}
